package com.neuedu.web;

import com.alibaba.fastjson.JSON;
import com.neuedu.utils.EchoUtils;
import com.neuedu.utils.PicEncode;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@WebServlet(name = "ArticleUploadimgServlet",urlPatterns = "/article/uploadimg")
public class ArticleUploadimgServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String base = request.getParameter("base");
        //删除字符串中非前缀信息
        base =base.replace("data:image/png;base64,","");
        //指定保存上传图片的文件夹
        String path = getServletContext().getRealPath(File.separator+"upload");
        //如果不存在该文件夹
        File file = new File(path);
        //如果不存在就创建
        if(!file.exists()){
            file.mkdir();
        }
        //上传图片
        String uuid = UUID.randomUUID().toString();
        //指定保存路径
        String strSavePath = path+File.separator+uuid+".jpg";
        //上传
        PicEncode.generateImage(base,strSavePath);
        //响应ajax请求
        EchoUtils echoUtils = new EchoUtils();
        echoUtils.setCode(1);
        echoUtils.setPath("upload/"+uuid+".jpg");
        //转json
        String str = JSON.toJSONString(echoUtils);
        response.getWriter().println(str);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
